package org.languageguide.readings;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

public class ApprovalUtil {


	public static void setApproval(HttpServletRequest request, java.sql.Connection connection, String readingId, String target, String field) throws SQLException{
		boolean approveAll;
		String approveAllStr = request.getParameter("approve_all");
		if (approveAllStr == null){
			approveAll = false;
		}
		else{
			approveAll = true;
		}
		System.out.println(approveAllStr + " " + approveAll);
		String sql = "SELECT " + field + " FROM `TranslatedReading` WHERE ReadingId = ? AND TargetLanguage = ?";
		System.out.println(sql);
		PreparedStatement select = connection.prepareStatement(sql);
		select.setString(1, readingId);
		select.setString(2, target);
		ResultSet set = select.executeQuery();
		if (set.next()){
			boolean approved = set.getBoolean(1);
			System.out.println("approved " + approved + " " + approveAll);
			if (approveAll != approved){
				sql = "UPDATE TranslatedReading SET  " + field + "  = ? WHERE ReadingId = ? AND TargetLanguage	=?";
				//System.out.println(sql + " " + approveAll + " " + readingId + " " + target);
				PreparedStatement updateStmt = connection.prepareStatement(sql);
				updateStmt.setBoolean(1, approveAll);
				updateStmt.setString(2, readingId);
				updateStmt.setString(3, target);
				updateStmt.executeUpdate();
			}
		}
		else{
			sql = "INSERT INTO TranslatedReading (ReadingId, TargetLanguage, ApprovedDefinitions) Values (?,?,?)";
			System.out.println(sql);
			PreparedStatement updateStmt = connection.prepareStatement(sql);
			updateStmt.setString(1, readingId);
			updateStmt.setString(2, target);
			updateStmt.setBoolean(3, approveAll);
			updateStmt.executeUpdate();
		}
	}	
	
}
